package org.example;

import cn.newdt.sshd.SshdConnection;
import cn.newdt.sshd.SshdSession;

import java.util.Optional;

/**
 * @author jiangjian
 * @desc SSH连接
 * @since 2023/6/30 10:45
 */
public class SshConn {

    public static void windows () throws Exception {
        try (SshdConnection sshdConnection = new SshdConnection("192.168.2.22")) {
            boolean authenticate = sshdConnection.authenticateWithPassword("test", "test");
            if (!authenticate) {
                throw new Exception("authenticateWithPassword fail");
            }
            // 执行命令
            SshdSession sshdSession = sshdConnection.openSession();
            try {
                sshdSession.execCommand("hostname", 30, 60);
                String result = sshdSession.getOkResult();
                System.out.println(result);
            } catch (Exception e) {
                String msg = Optional.ofNullable(e.getMessage()).orElse("");
                if (msg.contains("timeout")) {
                    throw new Exception("get session data time out");
                }
                throw e;
            }
        }
    }

}
